package com.example.partyplaner;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActionBar;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity implements AsyncResponse {
	public static final int PLEASE_WAIT_DIALOG = 1;
	public final static String LOGIN = "com.example.myfirstapp.LOGIN";
	public final static String PASSWORD = "com.example.myfirstapp.PASSWORD";
	public static String token; //token which needs to be passed with each get
	public static int noInternetMode=0 ; //token which needs to be passed with each get
	
	private Intent intent;
	public String address = "http://marek591.vdl.pl/product";
	private String responseMsg;
	private int responseCode;
	Button button1;
	Button button3;
	EditText input1;
	EditText input2;
	TextView tvIsConnected;
	public MenuItem internet;
	String filename = "login";	
	FileOutputStream outputStream;
	FileInputStream inputStream;
	
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		button3 = (Button) findViewById(R.id.button3);
		input1=(EditText)findViewById(R.id.input1);
		input2=(EditText)findViewById(R.id.input2);
		
		try {
			  //inputStream = openFileInput(filename);
			  FileInputStream fis = openFileInput(filename);
			  ObjectInputStream is = new ObjectInputStream(fis);
			  Login loginRead = (Login) is.readObject();
			  is.close();
			  
			  input1.setText(loginRead.email);
			  input2.setText(loginRead.password);
			  
			  outputStream.close();
			} catch (Exception e) {
			  e.printStackTrace();
			}

		
		button3.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (v.getId() == R.id.button3) {
					if (isConnected() == true) {
						noInternetMode=0;
						String result;
						JSONObject obj = new JSONObject();
						JSONArray req = new JSONArray();
						try {
							obj.put("email", input1.getText());
							obj.put("pass", input2.getText());
							req.put(obj);
						} catch (JSONException e) {
							e.printStackTrace();
						}
						DatabaseConnection db1 = new DatabaseConnection(MainActivity.this);
						db1.delegate = MainActivity.this;
						db1.execute("http://partyplanner.mais2014.cloudbees.net/rest/WebService/Login", "POST", req.toString());
					} 
					else {
						Toast toast=Toast.makeText(getApplicationContext(), "NO INTERNET CONNECTION", Toast.LENGTH_LONG);
				        LinearLayout toastLayout = (LinearLayout) toast.getView();
				        TextView toastTV = (TextView) toastLayout.getChildAt(0);
				        toastTV.setTextSize(30);
				        toastTV.setGravity(Gravity.CENTER_HORIZONTAL);
				        toast.show();
					}
				}
			}
		});
		
		
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	

	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.logout) {
			Intent intent = new Intent(getApplicationContext(),EventsActivity.class);
			startActivity(intent);
		}
		return super.onOptionsItemSelected(item);
	}

	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main, container,false);
			return rootView;
		}
	}

	public boolean isConnected() {
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnected())
			return true;
		else
			return false;
	}

	public Dialog onCreateDialog(int dialogId) {
		switch (dialogId) {
		case PLEASE_WAIT_DIALOG:
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setTitle("Connecting");
			dialog.setMessage("Please wait....");
			dialog.setCancelable(true);
			return dialog;
		default:
			break;
		}
		return null;
	}

	@Override
	public void processFinish(WebserviceResponse output) {
			if(output!=null){
				responseMsg=output.getResponseMsg();
				responseCode=output.getResponseCode();
				if (responseCode==200){
					if (responseMsg.charAt(0)=='f' && responseMsg.length()==1)
					{
						token="";
						Log.i("here","here");
						Toast toast=Toast.makeText(getApplicationContext(), "Not authorized", Toast.LENGTH_LONG);
				        LinearLayout toastLayout = (LinearLayout) toast.getView();
				        TextView toastTV = (TextView) toastLayout.getChildAt(0);
				        toastTV.setTextSize(30);
				        toastTV.setGravity(Gravity.CENTER_HORIZONTAL);
				        toast.show();
					}
					else{
						token=responseMsg;
						try {
							  outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
							  Login login=new Login(input1.getText().toString(),input2.getText().toString());
							  ObjectOutputStream os = new ObjectOutputStream(outputStream);
							  os.writeObject(login);
							 
							  os.close();
							  outputStream.close();
							} catch (Exception e) {
							  e.printStackTrace();
							}
						Intent intent = new Intent(getApplicationContext(),EventsActivity.class);
						startActivity(intent);
					}
				}
				else{
					token="";
					tvIsConnected.setText("Not Authorized");
					Toast toast=Toast.makeText(getApplicationContext(), "Not authorized", Toast.LENGTH_LONG);
			        LinearLayout toastLayout = (LinearLayout) toast.getView();
			        TextView toastTV = (TextView) toastLayout.getChildAt(0);
			        toastTV.setTextSize(30);
			        toastTV.setGravity(Gravity.CENTER_HORIZONTAL);
			        toast.show();
				}
			}
			else{
				Log.i("PartyPlanner", "NULL");
			}
	}
}
